package database

import (
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Paginate struct {
	Page     int         `json:"page"`
	List     interface{} `json:"list"`
	PageSize int         `json:"page_size"`
	Total    int64       `json:"total"`
}

func (p *Paginate) PaginateWithPageNameLimitName(c *gin.Context, pageName, limitName string) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		page, _ := strconv.Atoi(c.Request.FormValue(pageName))
		if page == 0 {
			page = 1
		}
		pageSize, _ := strconv.Atoi(c.Request.FormValue(limitName))
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		p.Page = page
		p.PageSize = pageSize
		offset := (page - 1) * pageSize
		tx := db.WithContext(c)
		tx.Count(&p.Total)

		return db.Offset(offset).Limit(pageSize)
	}
}

func (p *Paginate) Paginates(c *gin.Context) func(db *gorm.DB) *gorm.DB {
	return p.PaginateWithPageNameLimitName(c, "page", "limit")
}

func (p *Paginate) PaginateWithPageName(c *gin.Context, page string) func(db *gorm.DB) *gorm.DB {
	return p.PaginateWithPageNameLimitName(c, page, "limit")
}

func (p *Paginate) PaginateWithLimitName(c *gin.Context, limit string) func(db *gorm.DB) *gorm.DB {
	return p.PaginateWithPageNameLimitName(c, "page", limit)
}
